﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Hrm.Core;
using Hrm.EntityFramework;
using Hrm.Services;
using Hrm.Web.Framework;
using Microsoft.AspNet.Identity;

namespace Hrm.Web.Areas.Permissions.Controllers
{
    [RoleAuthorize]
    public class ApplicationsController : Controller
    {
        IApplicationService _applicationService;

        public ApplicationsController(IApplicationService applicationService)
        {
            _applicationService = applicationService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult PageApplications(PageRequest<ApplicationDto> request)
        {
            var result = _applicationService.GetPageList(request);
            return Json(result);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Application application)
        {
            if (ModelState.IsValid)
            {
                _applicationService.Insert(application);
                return RedirectToAction("Index");
            }

            return View(application);
        }

        public ActionResult Edit(int id = 0)
        {
            if (id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Application application = _applicationService.GetById(id);
            if (application == null)
            {
                return HttpNotFound();
            }
            return View(application);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Application application)
        {
            if (ModelState.IsValid)
            {
                var applicationToUpdate = _applicationService.GetById(application.Id);
                if (TryUpdateModel(applicationToUpdate, "", new string[] { "Id", "Name" }))
                {
                    _applicationService.Update(applicationToUpdate);
                }
                return RedirectToAction("Index");
            }
            return View(application);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            ResponseModel result = new ResponseModel();
            var model = _applicationService.GetById(id);
            if (model == null)
            {
                result.SetFailed("删除失败：没有你要删除的数据！");
                return Json(result);
            }
            _applicationService.UpdateDisabled(model);
            return Json(result);
        }
    }
}
